package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.config.VodConstantProperties;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.util.UploadFileUtil;
import com.atguigu.tingshu.vo.album.TrackMediaInfoVo;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
import com.qcloud.vod.VodUploadClient;
import com.qcloud.vod.model.VodUploadRequest;
import com.qcloud.vod.model.VodUploadResponse;
import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.vod.v20180717.VodClient;
import com.tencentcloudapi.vod.v20180717.models.*;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class VodServiceImpl implements VodService {

    @Resource
    private VodConstantProperties vodConstantProperties;

    @Override     //上传音频
    public Map<String, Object> uploadTrack(MultipartFile file) {
        try {
            //使用云 API 密钥初始化 VodUploadClient 实例
            VodUploadClient client = new VodUploadClient(vodConstantProperties.getSecretId(), vodConstantProperties.getSecretKey());
            //设置媒体本地上传路径
            VodUploadRequest request = new VodUploadRequest();
            //声音上传的临时目录
            String path = UploadFileUtil.uploadTempPath(vodConstantProperties.getTempPath(), file);
            request.setMediaFilePath(path);
            //调用上传方法，传入接入点地域及上传请求

            VodUploadResponse response = client.upload(vodConstantProperties.getRegion(), request);
            Map<String, Object> map = new HashMap<>();
            map.put("mediaFileId", response.getFileId());
            map.put("mediaUrl", response.getMediaUrl());
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override   //获取上传的音频详情
    public TrackMediaInfoVo getMediaDetail(String mediaFileId) {
        try {
            Credential cred = new Credential(vodConstantProperties.getSecretId(), vodConstantProperties.getSecretKey());

            VodClient client = new VodClient(cred, "");
            // 实例化一个请求对象,每个接口都会对应一个request对象
            DescribeMediaInfosRequest req = new DescribeMediaInfosRequest();
            String[] fileIds = {mediaFileId};
            req.setFileIds(fileIds);
            // 返回的resp是一个DescribeMediaInfosResponse的实例，与请求对象对应
            DescribeMediaInfosResponse resp = client.DescribeMediaInfos(req);
            MediaInfo[] mediaInfoSet = resp.getMediaInfoSet();
            if (!ArrayUtils.isEmpty(mediaInfoSet)) {
                MediaInfo mediaInfo = mediaInfoSet[0];
                TrackMediaInfoVo trackMediaInfoVo = new TrackMediaInfoVo();
                trackMediaInfoVo.setDuration(mediaInfo.getMetaData().getDuration());
                trackMediaInfoVo.setMediakUrl(mediaInfo.getBasicInfo().getMediaUrl());
                trackMediaInfoVo.setSize(mediaInfo.getMetaData().getSize());
                trackMediaInfoVo.setType(mediaInfo.getBasicInfo().getType());
                return trackMediaInfoVo;
            }
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void delMediaDetail(String mediaFileId) {
        try {
            Credential cred = new Credential(vodConstantProperties.getSecretId(), vodConstantProperties.getSecretKey());
            VodClient client = new VodClient(cred, "");
            // 实例化一个请求对象,每个接口都会对应一个request对象
            DeleteMediaRequest req = new DeleteMediaRequest();
            req.setFileId(mediaFileId);
            //执行删除请求
            client.DeleteMedia(req);
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getPlayToken(String mediaFileId) {
        Integer AppId = vodConstantProperties.getAppId();
        String AudioVideoType = "Original";
        Integer RawAdaptiveDefinition = 10;
        Integer ImageSpriteDefinition = 10;
        int CurrentTime = Math.toIntExact(new Date().getTime() / 1000);//播放器签名的派发时间为
        Integer pSignExpire = CurrentTime + 60 * 60 * 2;//播放器签名的过期时间，根据录制最长时间设置，如：两小时
        String UrlTimeExpire = String.valueOf(pSignExpire);//防盗链的过期时间
        String PlayKey = vodConstantProperties.getPlayKey();//播放密钥
        HashMap<String, Object> urlAccessInfo = new HashMap<String, Object>();
        urlAccessInfo.put("t", UrlTimeExpire);
        HashMap<String, Object> contentInfo = new HashMap<String, Object>();
        contentInfo.put("audioVideoType", AudioVideoType);
        contentInfo.put("rawAdaptiveDefinition", RawAdaptiveDefinition);
        contentInfo.put("imageSpriteDefinition", ImageSpriteDefinition);

        Algorithm algorithm = Algorithm.HMAC256(PlayKey);
        String token = JWT.create().withClaim("appId", AppId).withClaim("fileId", mediaFileId)
                .withClaim("contentInfo", contentInfo)
                .withClaim("currentTimeStamp", CurrentTime).withClaim("expireTimeStamp", pSignExpire)
                .withClaim("urlAccessInfo", urlAccessInfo).sign(algorithm);
        System.out.println("token:" + token);
        return token;
    }
}
